package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.delivery.Promotion;
import cn.itcast.bos.service.delivery.IPromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class PromotionAction extends BaseAction<Promotion>{
	private static final long serialVersionUID = 1L;
	//注入service
	@Autowired
	private IPromotionService promotionService;
	
	private File titleImgFile;
	private String titleImgFileFileName;

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	@Action(value="promotion_save", results={@Result(name="success", type="redirect"
			, location="./pages/take_delivery/promotion.html")})
	public String save() {
		//宣传图上传，保存宣传图路径到数据库
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
		String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";
		
		//生成随机图片名
		String uuid = UUID.randomUUID().toString().substring(1, 15);
		String imgName = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		String randomFileName = uuid + imgName;	//图片
		
		//保存图片
		File destFile = new File(savePath + "/" + randomFileName);
		try {
			FileUtils.copyFile(titleImgFile, destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//将相对路径
		model.setTitleImg(saveUrl + randomFileName);
		
		//保存数据
		promotionService.save(model);
		System.out.println("保存数据成功");
		
		return SUCCESS;
	}
	
	@Action(value="promotion_show", results={@Result(name="success", type="json")})
	public String pageShow() {
		//构造分页查询参数
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Promotion> pageData = promotionService.findPageData(pageable);
		pushPageDataToValueStack(pageData);
		
		return SUCCESS;
	}
}
